package com.zhangxun.interceptor;

import feign.RequestInterceptor;
import feign.RequestTemplate;

import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;


/**
 * 客户端之间远程调用请求头中的token设置
 */
@Component
public class FeignInterceptor implements RequestInterceptor {
    @Override
    public void apply(RequestTemplate requestTemplate) {

        //获取请求对象，拿到请求都对象中的token设置到请求模板对象中
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        String authorisation = request.getHeader("Authorization");
        if(authorisation != null){ //判断是否能拿到请求对象
            //拿到就设置到请求头中
            requestTemplate.header("Authorization",authorisation);
        }else{ //拿不到就使用写死的长期有效的token
            requestTemplate.header("Authorization","bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzY29wZSI6WyJjbGllbnQtc2NvcGUiXSwiZXhwIjozODE5NzIzMDA1LCJqdGkiOiJmMTk1NmQ0Ny1kMWE3LTQwODItOWJjYS1hM2ZhNmIyNTc4MmMiLCJjbGllbnRfaWQiOiJjbGllbnQifQ.eigo5dR_Cz1UU-i3Mrf42EzCu_H-gqCaS-87P9QQIMb1Qh-g80QppAy8gNHojMs9NcTzfwkofApEvaNuNCV81o8plMAiA4VapxfspjjQj0wHmzteDul5Nchhrs-xaCCTXL3ivsHLBn8eHXjsYhzsdb-vUv-Zu3PUTWPvdFixvaMvHPadFb72QKAYQ0DgwLB1AhQKd7PVOil4nianxC_ZcunMx6bg6ZB1aNfOMSuJ2saVDrf5S0mMNyY3r2NLzxpsELSMzJ9R19D-0W1IVMPL7AxpJErao44_rlK57TktXRVGoYB-PjTY_iUFBy4DQZHMB2oQckvwu_eS4uO6skQY8A");
        }
    }
}
